<template>
  <div class="right-panel">
    <div class="key-indicators-warning-card">
      <h3>关键指标预警</h3>
      <el-table
        :data="monitoredSensorsWithWarningStatus"
        stripe
        style="width: 100%"
        class="indicator-table"
        :row-class-name="({ row }) => (row.isWarn ? 'warning-row' : '')"
      >
        <el-table-column prop="id" label="传感器ID"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <span :class="row.isWarn ? 'status-warning-text' : 'status-normal-text'">
              {{ row.isWarn ? '预警' : '正常' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="latestValue" label="数值">
          <template #default="{ row }"> {{ row.latestValue }} {{ row.unit }} </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleShowSensorTrend(row.id)">
              Show
            </el-button>
          </template>
        </el-table-column>
        <template #empty>
          <p class="no-data-text-small">暂无关键指标</p>
        </template>
      </el-table>
    </div>

    <div class="alarm-management-card">
      <h3>关键指标报警</h3>
      <el-table
        :data="activeAlarmsList"
        stripe
        style="width: 100%"
        class="alarm-table"
        :row-class-name="
          ({ row }) =>
            !row.disposed && row.status !== '正常'
              ? 'undisposed-alarm-row'
              : row.status === '正常'
                ? 'normal-alarm-row'
                : 'disposed-alarm-row'
        "
      >
        <el-table-column prop="sensorId" label="传感器ID"></el-table-column>
        <el-table-column prop="statusText" label="状态">
          <template #default="{ row }">
            <span
              :class="{
                'status-undisposed-text': !row.disposed && row.status !== '正常',
                'status-disposed-text': row.disposed,
                'status-normal-alarm-text': row.status === '正常', // 新增正常状态文本样式
                clickable: !row.disposed && row.status !== '正常', // 只有未处置且非正常的才可点击
              }"
              @click="!row.disposed && row.status !== '正常' && handleAlarmStatusClick(row)"
            >
              {{ row.statusText }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="faultType" label="故障类型">
          <template #default="{ row }"> {{ row.faultType || '-' }} </template>
        </el-table-column>
        <el-table-column prop="time" label="时间">
          <template #default="{ row }">
            {{ row.time ? new Date(row.time).toLocaleTimeString('zh-CN', { hour12: false }) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="溯源">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleAnalyzeAlarm(row)">
              溯源
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="处置">
          <template #default="{ row }">
            <el-button
              link
              :type="row.disposed ? 'success' : 'warning'"
              size="small"
              :disabled="row.disposed || row.status === '正常'"
              @click="handleDisposeAlarm(row)"
            >
              {{ row.disposed ? '已处置' : '处置' }}
            </el-button>
          </template>
        </el-table-column>
        <template #empty>
          <p class="no-data-text-small">当前无报警信息</p>
        </template>
      </el-table>
      <el-button type="info" size="small" @click="emitViewFaultDetail" style="margin-top: 15px"
        >查看历史报警</el-button
      >
    </div>

    <div class="sensor-detail-chart-card">
      <div class="section-header">
        <h3>传感器详细趋势</h3>
        <el-button type="primary" size="small" @click="navigateToCustomChart">
          <!-- <el-button
          type="primary"
          size="small"
          @click="navigateToCustomChart"
          :disabled="!activeSensorId"
        > -->
          <i class="fas fa-chart-area"></i> 查看更多曲线
        </el-button>
      </div>
      <div class="chart-wrapper">
        <SensorDetailChart
          v-if="activeSensorId"
          :sensorId="activeSensorId"
          :deviceName="currentDevice"
        />
        <p v-else class="no-data-text" style="margin-top: 50px">
          请点击左侧设备示意图上的传感器方框查看详细趋势图。
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, computed, defineEmits } from 'vue'
import { ElButton, ElMessage, ElMessageBox, ElTable, ElTableColumn } from 'element-plus'
import SensorDetailChart from './SensorDetailChart.vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const props = defineProps({
  currentDevice: {
    type: String,
    required: true,
  },
  currentDeviceObject: {
    // 接收完整装置对象 (包含 id, name, info, sensorPoints)
    type: Object,
    default: () => ({ id: '', name: '', sensorPoints: [] }),
  },
  activeSensorId: {
    // 从 AnomalyDetectionMain 接收被点击的传感器ID
    type: String,
    default: null,
  },
})

const emit = defineEmits(['view-fault-detail', 'navigate-to-fault-tracing', 'sensor-clicked'])

// -------------------------------------------------------------
// 数据定义与辅助计算
// -------------------------------------------------------------

// 从后端获取的预警信息 (由 get_device_warnings 接口返回)
const deviceWarnings = ref([]) // [{ sensorId, latestValue, unit, isWarn }]

// 从后端获取的报警信息 (由 get_device_alarms 接口返回)
const deviceAlarms = ref([]) // [{ sensorId, alarmId, status, faultType, time, disposed }]

// 用于跟踪哪些预警 ElMessage 实例已经弹出
const activeWarningMessages = new Map() // key: sensorId, value: ElMessage instance

// 聚合所有主要和相关传感器，并附带后端返回的预警状态
const monitoredSensorsWithWarningStatus = computed(() => {
  const filteredSensors = props.currentDeviceObject.sensorPoints.filter(
    (point) => point.colorCategory === '主要' || point.colorCategory === '相关',
  )
  return filteredSensors.map((sensor) => {
    const warningStatus = deviceWarnings.value.find((warn) => warn.sensorId === sensor.id)
    return {
      ...sensor, // 包含 id, latestValue, unit, colorCategory
      isWarn: warningStatus ? warningStatus.isWarn : false, // 从后端获取的预警状态
      status: warningStatus ? (warningStatus.isWarn ? '预警' : '正常') : '正常', // 文本状态
    }
  })
})

// 计算属性：报警管理列表中显示的报警
const activeAlarmsList = computed(() => {
  // deviceAlarms 已经是后端返回的直接列表，包含正常、已处置和未处置的
  return deviceAlarms.value
    .map((alarm) => ({
      ...alarm,
      statusText: alarm.status === '正常' ? '正常' : alarm.disposed ? '报警已处置' : '报警未处置',
      faultType: alarm.faultType || '-', // 确保有默认值
    }))
    .sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime())
})

// -------------------------------------------------------------
// 数据获取
// -------------------------------------------------------------

/**
 * 从后端获取装置的预警信息。
 */
const fetchDeviceWarnings = async (deviceId) => {
  if (!deviceId) return
  try {
    console.log(
      `RightPanel: Fetching warnings for device ${deviceId} from /api/devices/${deviceId}/warnings...`,
    )
    const response = await fetch(`/api/devices/${deviceId}/warnings`)
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
    const data = await response.json()
    deviceWarnings.value = data
    console.log(`RightPanel: Warnings loaded for ${deviceId}.`, deviceWarnings.value)
  } catch (error) {
    console.error(`RightPanel: Error fetching warnings for ${deviceId}, using mock:`, error)
    // Fallback mock warnings based on current sensorPoints
    deviceWarnings.value = props.currentDeviceObject.sensorPoints
      .filter((p) => p.colorCategory === '主要' || p.colorCategory === '相关')
      .map((s) => ({
        sensorId: s.id,
        latestValue: s.latestValue,
        unit: s.unit,
        isWarn: s.id === 'FIC1002' || s.id === 'TE203' ? true : false, // Example mock warnings
      }))
  }
}

/**
 * 从后端获取装置的报警信息。
 */
const fetchDeviceAlarms = async (deviceId) => {
  if (!deviceId) return
  try {
    console.log(
      `RightPanel: Fetching alarms for device ${deviceId} from /api/devices/${deviceId}/alarms...`,
    )
    const response = await fetch(`/api/devices/${deviceId}/alarms`)
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
    const data = await response.json()
    // 直接赋值后端返回的数组
    deviceAlarms.value = data
    console.log(`RightPanel: Alarms loaded for ${deviceId}.`, deviceAlarms.value)
  } catch (error) {
    console.error(`RightPanel: Error fetching alarms for ${deviceId}, using mock:`, error)
    // Fallback mock alarms: Include both normal and alarm statuses
    deviceAlarms.value = [
      // Normal sensor
      {
        sensorId: 'FIC1001',
        alarmId: null,
        status: '正常',
        faultType: null,
        time: new Date().toISOString(),
        disposed: true,
      },
      // Undisposed alarm
      {
        sensorId: 'FIC1002',
        alarmId: 'mock_alarm_2',
        time: new Date().toISOString(),
        type: '通信故障(MOCK)',
        status: '未处置',
        disposed: false,
      },
      // Disposed alarm
      {
        sensorId: 'PIC1003',
        alarmId: 'mock_alarm_3',
        time: new Date(Date.now() - 3600 * 1000).toISOString(),
        type: '压力超限(MOCK)',
        status: '已处置',
        disposed: true,
      },
    ]
  }
}

/**
 * 处置报警 (调用后端接口)。
 */
const disposeAlarmBackend = async (alarmId) => {
  try {
    console.log(`RightPanel: Disposing alarm ${alarmId} via backend.`)
    const response = await fetch(`/api/alarms/${alarmId}/dispose`, { method: 'POST' })
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
    const result = await response.json()
    if (!result.success) throw new Error(result.message || 'Backend dispose failed')
    console.log(`RightPanel: Alarm ${alarmId} disposed successfully on backend.`)
    return true
  } catch (error) {
    console.error(`RightPanel: Failed to dispose alarm ${alarmId} on backend:`, error)
    ElMessage.error(`处置报警失败: ${error.message}`)
    return false
  }
}

// -------------------------------------------------------------
// 上：关键指标预警逻辑 (表格，点击行显示详情，预警弹窗)
// -------------------------------------------------------------

/**
 * 处理预警行点击，如果预警，弹窗显示预警信息。
 * @param {Object} sensor - 触发预警的传感器对象。
 */
const showWarningDetails = (sensor) => {
  // 仅当 sensor.isWarn 为 true (预警状态) 且当前没有活跃的预警通知时才弹窗
  if (sensor.isWarn && !activeWarningMessages.has(sensor.id)) {
    const alarmDetails = `传感器 ${sensor.id} (${sensor.latestValue} ${sensor.unit}) 值超限，请立即关注！`
    const messageInstance = ElMessage({
      showClose: true,
      message: alarmDetails,
      type: 'warning',
      duration: 0, // 不自动关闭
      onClose: () => {
        // 当消息框手动关闭时，从Map中移除
        activeWarningMessages.delete(sensor.id)
        console.log(`RightPanel: Warning message for ${sensor.id} closed.`)
      },
    })
    activeWarningMessages.set(sensor.id, messageInstance)
    console.log(`RightPanel: Warning triggered for ${sensor.id}: ${alarmDetails}`)
  }
}

/**
 * 处理“Show”按钮点击，传递传感器ID给详细趋势图。
 * @param {string} sensorId - 被点击传感器的ID。
 */
const handleShowSensorTrend = (sensorId) => {
  emit('sensor-clicked', sensorId) // 向上发出 'sensor-clicked' 事件
}

// -------------------------------------------------------------
// 中：报警管理逻辑 (表格，点击状态跳转，点击处置按钮处置)
// -------------------------------------------------------------

/**
 * 处理“报警状态”点击，未处置的跳转到故障溯源。
 * @param {Object} alarm - 被点击的报警对象 (从 activeAlarmsList 来)。
 */
const handleAlarmStatusClick = (alarm) => {
  // 只有未处置且非“正常”状态的报警才跳转
  if (alarm && !alarm.disposed && alarm.status !== '正常') {
    console.log(`RightPanel: Alarm ${alarm.alarmId} status clicked. Navigating to Fault Tracing.`)
    ElMessage({
      message: `正在跳转到故障溯源页面进行分析 ${alarm.sensorId}`,
      type: 'info',
      duration: 2000,
    })
    emit('navigate-to-fault-tracing', { alarmId: alarm.alarmId, sensorId: alarm.sensorId })
  } else if (alarm.disposed) {
    ElMessage({
      message: `报警 ${alarm.alarmId} 已处置，无需分析。`,
      type: 'success',
      duration: 1500,
    })
  } else if (alarm.status === '正常') {
    ElMessage({
      message: `传感器 ${alarm.sensorId} 状态正常，无需分析。`,
      type: 'info',
      duration: 1500,
    })
  }
}

/**
 * 处理“原因分析”按钮点击。
 * @param {Object} alarm - 被点击的报警对象。
 */
const handleAnalyzeAlarm = (alarm) => {
  console.log(
    `RightPanel: Analyzing alarm ${alarm.alarmId || alarm.sensorId}. Navigating to Fault Tracing.`,
  )
  ElMessage({
    message: `正在跳转到故障溯源页面分析报警 ${alarm.sensorId}`,
    type: 'info',
    duration: 2000,
  })
  emit('navigate-to-fault-tracing', {
    alarmId: alarm.alarmId || 'N/A',
    sensorId: alarm.sensorId,
    type: 'analysis',
  })
}

/**
 * 处理“处置”按钮点击，标记报警为已处置 (通过后端接口)。
 * @param {Object} alarm - 被点击的报警对象。
 */
const handleDisposeAlarm = async (alarm) => {
  // 只有未处置且非“正常”状态的报警才能点击处置
  if (alarm && !alarm.disposed && alarm.status !== '正常') {
    const disposedSuccess = await disposeAlarmBackend(alarm.alarmId) // 调用后端接口
    if (disposedSuccess) {
      // 成功后，更新前端 deviceAlarms 状态
      const foundAlarm = deviceAlarms.value.find((a) => a.alarmId === alarm.alarmId)
      if (foundAlarm) {
        // 使用 Vue 3 响应式地更新数组中的对象
        foundAlarm.disposed = true
        foundAlarm.status = '已处置'
        foundAlarm.disposedTime = new Date().toISOString()
      }
      ElMessage({
        message: `报警 ${alarm.sensorId} 已标记为处置！`,
        type: 'success',
        duration: 2000,
      })
    }
  } else if (alarm.disposed) {
    ElMessage({
      message: `报警 ${alarm.sensorId} 已处置，无需重复操作。`,
      type: 'info',
      duration: 1500,
    })
  } else if (alarm.status === '正常') {
    ElMessage({
      message: `传感器 ${alarm.sensorId} 状态正常，无需处置。`,
      type: 'info',
      duration: 1500,
    })
  }
}

/**
 * 处理“查看历史报警”按钮点击，跳转到故障信息列表页。
 */
const emitViewFaultDetail = () => {
  emit('view-fault-detail')
}

// -------------------------------------------------------------
// 下：传感器详细趋势（保持不变）
// -------------------------------------------------------------

// -------------------------------------------------------------
// 生命周期钩子与监听
// -------------------------------------------------------------

const navigateToCustomChart = () => {
  if (props.activeSensorId && props.currentDeviceObject?.id) {
    router.push({
      name: 'CustomChart', // 对应 router/index.js 中定义的路由名称
      query: {
        deviceId: props.currentDeviceObject.id,
        sensorId: props.activeSensorId, // 将当前选中的传感器ID作为查询参数传递
      },
    })
  } else {
    router.push({ name: 'CustomChart' }) // 如果没有选中传感器，直接跳转
  }
}

let warningCheckInterval = null // 在顶层声明，确保 onUnmounted 可以访问到

onMounted(() => {
  console.log('RightPanel: Component mounted.')

  // 持续检查预警状态，以便当传感器值恢复正常时关闭预警弹窗
  warningCheckInterval = setInterval(() => {
    monitoredSensorsWithWarningStatus.value.forEach((sensor) => {
      // 如果传感器不再预警，且有活跃的预警通知，就关闭它
      if (!sensor.isWarn && activeWarningMessages.has(sensor.id)) {
        const msgInstance = activeWarningMessages.get(sensor.id)
        if (msgInstance && typeof msgInstance.close === 'function') {
          msgInstance.close()
          activeWarningMessages.delete(sensor.id)
          ElMessage({
            message: `传感器 ${sensor.id} 已恢复正常，预警状态解除。`,
            type: 'info',
            duration: 2000,
          })
        }
      }
    })
  }, 1000) // 每秒检查一次
})

onUnmounted(() => {
  // 清理定时器
  if (warningCheckInterval) {
    clearInterval(warningCheckInterval)
  }
  // 关闭所有活跃的预警弹窗
  activeWarningMessages.forEach((msgInstance) => msgInstance.close())
  activeWarningMessages.clear()
})

// 监听 currentDeviceObject.id 变化，获取后端数据 (预警和报警)
watch(
  () => props.currentDeviceObject.id,
  async (newDeviceId, oldDeviceId) => {
    if (newDeviceId) {
      console.log(
        `RightPanel: currentDeviceObject.id changed to ${newDeviceId}. Fetching warnings and alarms.`,
      )
      await fetchDeviceWarnings(newDeviceId) // 获取预警信息
      await fetchDeviceAlarms(newDeviceId) // 获取报警信息
      // 清除所有活跃的预警弹窗，避免跨装置混淆
      activeWarningMessages.forEach((msgInstance) => msgInstance.close())
      activeWarningMessages.clear()
    } else if (oldDeviceId) {
      // 装置切换到无设备时，清空
      deviceWarnings.value = []
      deviceAlarms.value = []
      activeWarningMessages.forEach((msgInstance) => msgInstance.close())
      activeWarningMessages.clear()
    }
  },
  { immediate: true },
) // 立即执行一次以处理初始加载

// 监听 activeSensorId 的变化，用于传感器详细趋势图表的更新 (保持不变)
watch(
  () => props.activeSensorId,
  (newId) => {
    console.log(`RightPanel: Active sensor ID for chart changed to: ${newId}`)
  },
)

// Removed addAlarm simulation from onMounted to avoid confusion with backend data.
// If you want to simulate new alarms, you can call addAlarm explicitly based on some other event or timer.
</script>

<style scoped>
.right-panel {
  flex: 1.2;
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-height: 0;
  background-color: #f0f2f5;
  padding: 0;
}

/* 统一的卡片基础样式 */
.key-indicators-warning-card,
.alarm-management-card,
.sensor-detail-chart-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  min-height: 0;
  box-sizing: border-box;
}

/* Flex 比例分配 */
.key-indicators-warning-card {
  max-height: 400px;
}
.alarm-management-card {
  max-height: 600px;
}
.sensor-detail-chart-card {
}

/* 统一的标题样式 */
h3 {
  color: #3f51b5;
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 1.1em;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  flex-shrink: 0;
}

.no-data-text,
.no-data-text-small {
  color: #888;
  text-align: center;
  margin-top: 10px;
  font-size: 0.9em;
}
.no-data-text-small {
  font-size: 0.8em;
  margin-top: 5px;
}

/* 关键指标预警 (表格) 样式 */
.indicator-table {
  width: 100%;
  font-size: 0.9em;
}
.indicator-table .status-normal-text {
  color: #388e3c; /* 绿色 */
  font-weight: bold;
}
.indicator-table .status-warning-text {
  color: #d35400; /* 深橙色 */
  font-weight: bold;
}
.indicator-table .warning-row {
  background-color: #ffe0b2; /* 预警行背景色 */
}
/* 预警行无动画 */

/* 报警管理 (表格) 样式 */
.alarm-table {
  width: 100%;
  font-size: 0.9em;
}
.alarm-table .status-undisposed-text {
  color: #ef6c00; /* 橙色 */
  font-weight: bold;
}
.alarm-table .status-disposed-text {
  color: #388e3c; /* 绿色 */
  font-weight: bold;
}
.alarm-table .status-normal-alarm-text {
  /* 正常状态文本颜色 */
  color: #388e3c; /* 绿色 */
  font-weight: bold;
}

.alarm-table .undisposed-alarm-row {
  background-color: #fff3e0; /* 未处置报警行背景 */
}
.alarm-table .undisposed-alarm-row .status-undisposed-text {
  animation: pulse-undisposed 0.8s infinite alternate; /* 未处置报警闪烁 */
}
@keyframes pulse-undisposed {
  from {
    box-shadow:
      0 0 3px #ffb74d,
      0 0 6px #ffb74d80;
  }
  to {
    box-shadow:
      0 0 6px #ffb74d,
      0 0 12px #ffb74d80;
  }
}

.alarm-table .disposed-alarm-row {
  background-color: #e8f5e9; /* 已处置报警行背景 */
}
.alarm-table .normal-alarm-row {
  /* 正常状态行背景 */
  background-color: #f8f8f8; /* 默认或稍浅 */
}

/* 传感器详细趋势样式 */
.sensor-detail-chart-card {
  width: 100%;
}
.chart-wrapper {
  position: relative;
  height: 380px;
  width: 100%;
  margin-top: 10px;
  flex-shrink: 0;
  background-color: #f9f9f9;
  border-radius: 4px;
  padding: 10px;
  box-sizing: border-box;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
  flex-shrink: 0; /* 防止标题收缩 */
}

.section-header h3 {
  margin: 0; /* 覆盖默认的h3 margin */
  border-bottom: none; /* 移除h3自带的下划线，因为父级section-header已经有 */
  padding-bottom: 0;
}
</style>
